package com.example.dbsample.filter;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.servlet.ReadListener;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


/**
 * XSS过滤处理
 * 参考：https://blog.csdn.net/nxllong/article/details/78142857
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {



    private static final Pattern SQL_PATTERN1 = Pattern.compile("/((\\%3D)|(=))[^\\n]*((\\%27)|(\\’)|(\\-\\-)|(\\%3B)|(:))/ix");
    private static final Pattern SQL_PATTERN2 = Pattern.compile("/\\w*((\\%27)|(\\'))((\\%6F)|o|(\\%4F))((\\%72)|r|(\\%52))/ix");
    private static final Pattern SQL_PATTERN3 = Pattern.compile("/((\\%27)|(\\'))union/ix");
    private static final Pattern SCRIPT_PATTERN = Pattern.compile("<script.*>.*<\\/script\\s*>");
    private static final Pattern HTML_PATTERN = Pattern.compile("<[^>]+>");
    //没被包装过的HttpServletRequest（特殊场景，需要自己过滤）
    HttpServletRequest orgRequest;
    //html过滤
    private final static HTMLFilter htmlFilter = new HTMLFilter();


    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest = request;
    }


    @Override
    public ServletInputStream getInputStream() throws IOException {
        //非json类型，直接返回
        if(!super.getHeader(HttpHeaders.CONTENT_TYPE).equalsIgnoreCase(MediaType.APPLICATION_JSON_VALUE)) {
            return super.getInputStream();
        }

        // 为空，直接返回
        String checkedStr = IOUtils.toString(super.getInputStream(), "utf-8");
        if(StringUtils.isBlank(checkedStr)) {
            return super.getInputStream();
        }

        // xss过滤
        checkedStr = xssEncode(checkedStr);


            //checkedStr=CheckedStr(checkedStr);
            //checkedStr=sqlFactionChecked(checkedStr);

        final ByteArrayInputStream bis = new ByteArrayInputStream(checkedStr.getBytes("utf-8"));
        return new ServletInputStream() {
            @Override
            public boolean isFinished() {
                return false;
            }

            @Override
            public boolean isReady() {
                return false;
            }

            @Override
            public void setReadListener(ReadListener readListener) {

            }

            @Override
            public int read() throws IOException {
                return bis.read();
            }
        };
    }


    //    //为空，直接返回
    //    String json = IOUtils.toString(super.getInputStream(), "utf-8");
    //    if (StringUtils.isBlank(json)) {
    //        return super.getInputStream();
    //    }
    //    json=CheckedStr(json);
    //
    //    //自己添加的 SQL函数
    //    json=sqlFactionChecked(json);
    //
    //    //xss过滤
    //    json = xssEncode(json);
    //
    //    //sql注入过滤
    //    json = sqlInject(json);
    //
    //    final ByteArrayInputStream bis = new ByteArrayInputStream(json.getBytes("utf-8"));
    //    return new ServletInputStream() {
    //        public boolean isFinished() {
    //            return true;
    //        }
    //
    //
    //        public boolean isReady() {
    //            return true;
    //        }
    //
    //        @Override
    //        public void setReadListener(ReadListener readListener) {
    //
    //        }
    //
    //
    //        public void setReadListener(ReaderEventListener readListener) {
    //
    //
    //        }
    //
    //
    //        @Override
    //        public int read() throws IOException {
    //            return bis.read();
    //        }
    //    };
    //}


    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }


    @Override
    public String[] getParameterValues(String name) {
        String[] parameters = super.getParameterValues(name);
        if (parameters == null || parameters.length == 0) {
            return null;
        }


        for (int i = 0; i < parameters.length; i++) {
            parameters[i] = xssEncode(parameters[i]);
        }
        return parameters;
    }


    @Override
    public Map<String,String[]> getParameterMap() {
        Map<String,String[]> map = new LinkedHashMap<String, String[]>();
        Map<String,String[]> parameters = super.getParameterMap();
        for (String key : parameters.keySet()) {
            String[] values = parameters.get(key);
            for (int i = 0; i < values.length; i++) {
                values[i] = xssEncode(values[i]);
            }
            map.put(key, values);
        }
        return map;
    }

    @Override
    public String getHeader(String name) {
        String value = super.getHeader(xssEncode(name));
        if (StringUtils.isNotBlank(value)) {
            value = xssEncode(value);
        }
        return value;
    }


    private String xssEncode(String input) {
        return htmlFilter.filter(input);
    }


    private String sqlInject(String str) {
        if(StringUtils.isBlank(str)){
            return null;
        }
        //去掉'|"|;|\字符
        str = StringUtils.replace(str, "'", "");
        str = StringUtils.replace(str, "\"", "");
        str = StringUtils.replace(str, ";", "");
        str = StringUtils.replace(str, "\\", "");

        //转换成小写
//        str = str.toLowerCase();


        //非法字符
        String[] keywords = {"master", "truncate", "insert", "select", "delete", "update", "declare", "alert", "drop"};


        //判断是否包含非法字符
        for(String keyword : keywords){
            if(str.indexOf(keyword) != -1){
                str = StringUtils.replace(str, keyword, "");
            }
        }


        return str;
    }


    public String sqlFactionChecked(String str) {
        str = regexReplace(SQL_PATTERN1, "", str);
        str = regexReplace(SQL_PATTERN2, "", str);
        str = regexReplace(SQL_PATTERN3, "", str);
        // 过滤sql转换函数
        str= StringEscapeUtils.escapeSql(str);
        str = StringUtils.replace(str,"%20 ", "");
        str = StringUtils.replace(str,"%3E ", "");
        str = StringUtils.replace(str,"%27 ", "");
        str = StringUtils.replace(str,"chr[(] ", "");
        str = StringUtils.replace(str,"chr [(] ", "");
        str = StringUtils.replace(str,"ascii [(] ", "");
        str = StringUtils.replace(str,"ascii[(] ", "");
        // 过滤sql函数
        str = StringUtils.replace(str,"create ", "");
        str = StringUtils.replace(str,"truncate ", "");
        str = StringUtils.replace(str,"drop ", "");
        str = StringUtils.replace(str,"insert ", "");
        str = StringUtils.replace(str,"delete ", "");
        str = StringUtils.replace(str,"select ", "");
        str = StringUtils.replace(str,"lock table ", "");
        str = StringUtils.replace(str,"update ", "");
        return str;
    }
    public String CheckedStr(String str) {

        str = regexReplace(SCRIPT_PATTERN, "", str);
        str = regexReplace(HTML_PATTERN, "", str);
        str = StringUtils.replace(str,"%27 ", "");
        str = StringUtils.replace(str,"&","&" );
        str = StringUtils.replace(str,"<","<");
        str = StringUtils.replace(str,">",">");
        str = StringUtils.replace(str,"\"","\\\"");  // 这个不知道怎么弄
        str = StringUtils.replace(str,"<", "");
        str = StringUtils.replace(str,">", "");
        str = StringUtils.replace(str,"ScRipt", "");
        str = StringUtils.replace(str,"script", "");
        str = StringUtils.replace(str,"WEB-INF", "");
        str = StringUtils.replace(str,"../", "");
        str = StringUtils.replace(str,"./", "");
        str = StringUtils.replace(str,"%20", "");
        str = StringUtils.replace(str,".java", "");
        str = StringUtils.replace(str,".xml", "");
        str = StringUtils.replace(str,".class", "");
        str = StringUtils.replace(str,"alert", "");
        str = StringUtils.replace(str,"%3E", "");
        return str;
    }

    private static String regexReplace(final Pattern regex_pattern, final String replacement, final String s) {
        Matcher m = regex_pattern.matcher(s);
        return m.replaceAll(replacement);
    }
    /**
     * 获取最原始的request
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }


    /**
     * 获取最原始的request
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest request) {
        if (request instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) request).getOrgRequest();
        }
        return request;
    }
}
